<template>
    <div>
        <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="() => { $router.push('/') }" fixed />
        <div style="height: 45px;"></div>
        <div v-for="i in data">
            <van-card :price="i.goods.goods_price" :title="i.goods.goods_name">
                <template #thumb>
                    <van-checkbox v-model="i.checked"></van-checkbox>
                    <img :src="i.goods.goods_big_logo ? i.goods.goods_big_logo : 'https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg'"
                        alt="" style="width: 70px;">
                </template>
                <template #num>
                    <van-stepper v-model="i.number" theme="round" button-size="22" disable-input />
                </template>
            </van-card>
        </div>
        <van-submit-bar :price="priceall" button-text="提交订单" @submit="onSubmit">
            <van-checkbox v-model="checkedall">全选</van-checkbox>
        </van-submit-bar>
    </div>
</template>

<script setup>
import { computed, ref } from 'vue'
let data = ref([])
import { useCounterStore } from '@/stores/car.js'
// 可以在组件中的任意位置访问 `store` 变量 ✨
const store = useCounterStore()
const gocar = () => {
    let username = localStorage.getItem('username')
    data.value = store.carts.filter(item => item.username == username)
}
gocar()
import { createApi } from '@/api/api'
import { showToast } from 'vant';
const checkedall = computed({
    get(){
        return data.value.every(item => item.checked)
    },
    set(value){
        data.value.forEach(item => {
            item.checked = value
        })
    },
})

let priceall = computed(() => {
    let sum=0
    data.value.forEach(item => {
        if (item.checked) {
            sum += item.number * item.goods.goods_price
        }
    })
    return sum*100
})
import { useRouter } from 'vue-router'
const router = useRouter()
const onSubmit = () => {
    let checked = data.value.filter(item => item.checked)
    if (checked.length == 0) {
        showToast({
            message: '购物车暂无数据',
            type:'fail',
            icon: 'like-o',
        });
    }
    else{
        createApi({
            goodsIds: checked.map(item => item.goods.goods_id).join(','),
            username: localStorage.getItem('username'),
            product_code:checked[0].goods.goods_name,
            totalPrice: priceall.value / 100,
            nums: checked.map(item => item.number).join(',')
        }).then(res=>{
            console.log(res);
            router.push('/order/'+res.data.data.orderId)
        })
    }
}
</script>

<style lang="scss" scoped></style>